import React from 'react';
import {Menu} from 'antd';
import './index.less';
import MenuConfig from './../../config/menuConfig';
import {NavLink} from 'react-router-dom';
import {connect} from "react-redux";
import {switchMenu} from './../../redux/action'

const SubMenu = Menu.SubMenu;

class NavLeft extends React.Component {
    state = {
        currentKey: ''
    }


    componentWillMount() {
        const menuTreeNode = this.renderMenu(MenuConfig);
        let currentKey = window.location.hash.replace(/#|\?.*$/g, '')
        this.setState({
            currentKey,
            menuTreeNode
        })
    }


     // 触发action里面的switchMenu事件
    handleChange = ({item,key}) => {

        //dispatch只有在connect当前组件后，才可以从props里面取到
        const {dispatch} = this.props;
        dispatch(switchMenu(item.props.title));

        this.setState({
            currentKey: key
        })
    };

    /**
     *  根据菜单树展示菜单栏（菜单渲染）
     * @author  姚格格
     * @date    2020-03-16 14:26
     */
        // 菜单渲染
    renderMenu = (data) => {
        return data.map((item) => {
            if (item.children) {
                return (
                    <SubMenu title={item.title} key={item.key}>
                        {this.renderMenu(item.children)}
                    </SubMenu>
                )
            }
            return <Menu.Item title={item.title} key={item.key}>
                <NavLink to={item.key}>{item.title}</NavLink>
            </Menu.Item>
        })
    }

    render() {
        return (
            <div>
                <div className="logo">
                    <img alt="" src="/assets/logo-ant.svg"/>
                    <h1> Imooc MS</h1>

                </div>
                <Menu
                    //定位到当前选中菜单
                    onClick={this.handleChange}
                    selectedKeys={[this.state.currentKey]}
                    theme="dark">
                    {this.state.menuTreeNode}
                </Menu>

            </div>
        );
    }

}

//connect
export default connect()(NavLeft)
